package cleandisk

import java.io.File
import util.Elvis.elvisOperator

/**
 * <p>
 * Created by IntelliJ IDEA.
 * User: zslajchrt
 * Date: Sep 10, 2010
 * Time: 2:14:51 PM
 */

object CleanDisk extends Application {
  val MAX_MAX = 20
  val excludes: Set[String] = Set("/Users/zslajchrt/Documents/Parallels/Microsoft Windows XP.pvm/winxp.hdd/winxp.hdd.0.{5fbaabe3-6958-40ff-92a7-860e329aab41}.hds",
    "/Users/zslajchrt/Documents/Parallels/Microsoft Windows XP.pvm/{93ce3884-f0d4-4aa7-9ea1-4eeb9afbd887}.mem")

  clean(new File("/System/Library"), List())

  def clean(dir: File, topMaxs: List[File]): List[File] = {
    var newTopMaxs: List[File] = topMaxs

    def printMaxs: Unit = {
      newTopMaxs.foreach(mf => print(mf.getPath + "(" + mf.length + "),"))
      println
    }

    (dir.listFiles ?: Array()).foreach(f => {
      if (!excludes.contains(f.getPath)) {
        val localMaxs = if (f.isDirectory) {
          newTopMaxs = clean(f, newTopMaxs)
        } else {
          val fileLength = f.length
          val lastLessIndex = newTopMaxs.lastIndexWhere(m => m.length < fileLength)
          if (lastLessIndex < 0) {
            newTopMaxs = f :: newTopMaxs
          } else {
            val (ml1, ml2) = newTopMaxs.splitAt(lastLessIndex + 1)
            newTopMaxs = ml1 ::: (f :: ml2)
            printMaxs
          }
        }

        if (newTopMaxs.length > MAX_MAX) newTopMaxs = newTopMaxs.takeRight(MAX_MAX)
      }

    })
    newTopMaxs
  }

}